import axios from 'axios';
import JSEncrypt from 'jsencrypt';
import config from './config';
import { closeToast, showFailToast } from 'vant';

const { authServerUrl, qmsServerUrl } = config;

const getPublicKeyFnStr: string = `${authServerUrl}/base/tools/v1/getPublicKey`;

async function getPublicKey(): Promise<any> {
  return axios({
    method: 'GET',
    url: getPublicKeyFnStr,
  })
}

/**
 * RSA加密
 * @param password
 * @returns {Promise<{param: PromiseLike<ArrayBuffer>}|*>}
 */
async function encryptedData(password: string): Promise<string | false> {
  let publicKey: string = '';
  const res = await getPublicKey();
  publicKey = res.data.value;
  if (publicKey == '') {
    return password;
  }
  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(publicKey);
  return encrypt.encrypt(password);
}

const request = axios.create({});

request.defaults.timeout = 10000;

request.defaults.headers['Content-Type'] = 'application/json';

const noAuthFilterArr = [
  `${authServerUrl}/auth`,
  getPublicKeyFnStr,
];

function noAuth(url: string | undefined) {
  if (!url) {
    return false;
  }
  for (let i = 0; i < noAuthFilterArr.length; i++) {
    if (url.indexOf(noAuthFilterArr[i]) > -1) {
      return true;
    }
  }
  return false;
}

request.interceptors.request.use(
  (config) => {
    if (!noAuth(config.url)) {
      const token: string | null = sessionStorage.getItem('token');
      if (!!token) {
        config.headers.Authorization = `Bearer ${token}`
      }
    }
    return config;
  },
  (error) => { }
)

request.interceptors.response.use(
  (config) => {
    closeToast();
    return config;
  },
  (error) => {
    console.error(error)
    if (error.code == 'ECONNABORTED' || error.code == 'ERR_NETWORK') {
      showFailToast({
        message: '请检查网络是否正常',
        duration: 1500,
      });
    } else {
      showFailToast({
        message: error.response?.data.message || '后台接口异常',
        duration: 1500,
      });
    }
  }
)

export { request, encryptedData };
